﻿using System;
using System.Collections.Generic;
using System.Text;

namespace GraffitiExtras.Plugins.IPBlocker
{
    internal class CompareIPs
    {
        #region Public methods

        static public bool AreEqual(string IPAddress1, string IPAddress2)
        {
            // convert to long in case there is any zero padding in the strings
            return IPAddressToLongBackwards(IPAddress1) == IPAddressToLongBackwards(IPAddress2);
        }

        static public bool IsGreater(string ToCompare, string CompareAgainst)
        {
            // convert to long in case there is any zero padding in the strings
            return IPAddressToLongBackwards(ToCompare) > IPAddressToLongBackwards(CompareAgainst);
        }

        static public bool IsLess(string ToCompare, string CompareAgainst)
        {
            // convert to long in case there is any zero padding in the strings
            return IPAddressToLongBackwards(ToCompare) < IPAddressToLongBackwards(CompareAgainst);
        }

        static public bool IsGreaterOrEqual(string ToCompare, string CompareAgainst)
        {
            // convert to long in case there is any zero padding in the strings
            return IPAddressToLongBackwards(ToCompare) >= IPAddressToLongBackwards(CompareAgainst);
        }

        static public bool IsLessOrEqual(string ToCompare, string CompareAgainst)
        {
            // convert to long in case there is any zero padding in the strings
            return IPAddressToLongBackwards(ToCompare) <= IPAddressToLongBackwards(CompareAgainst);
        }


        static public string LongToIPAddress(uint IPAddress)
        {
            return new System.Net.IPAddress(IPAddress).ToString();
        }

        static public uint IPAddressToLong(string IPAddress)
        {
            System.Net.IPAddress oIP = System.Net.IPAddress.Parse(IPAddress);
            byte[] byteIP = oIP.GetAddressBytes();


            uint ip = (uint)byteIP[3] << 24;
            ip += (uint)byteIP[2] << 16;
            ip += (uint)byteIP[1] << 8;
            ip += (uint)byteIP[0];

            return ip;
        }

        #endregion

        #region Private methods

        static private uint IPAddressToLongBackwards(string IPAddress)
        {
            System.Net.IPAddress oIP = System.Net.IPAddress.Parse(IPAddress);
            byte[] byteIP = oIP.GetAddressBytes();


            uint ip = (uint)byteIP[0] << 24;
            ip += (uint)byteIP[1] << 16;
            ip += (uint)byteIP[2] << 8;
            ip += (uint)byteIP[3];

            return ip;
        }

        #endregion
    }
}
